package com.macro.cloud.executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.concurrent.*;

@Service
public class TimerService {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    //--------------------守护线程----------------------------
    static ScheduledExecutorService scheduledExecutor = Executors
            .newSingleThreadScheduledExecutor(new ThreadFactory() {
                @Override
                public Thread newThread(Runnable r) {
                    Thread t = new Thread(r);
                    t.setName("守护线程----xxxx----");
                    t.setDaemon(true);
                    return t;
                }
            });

    //延迟任务
    static public void scheduleWithFixedDelay(Runnable command, long initialDelay,
                                              long delay, TimeUnit unit) {
        scheduledExecutor.scheduleWithFixedDelay(command, initialDelay, delay, unit);
    }

    //周期任务
    static public void scheduleAtFixedRate(Runnable command, long initialDelay,
                                           long delay, TimeUnit unit) {
        scheduledExecutor.scheduleAtFixedRate(command, initialDelay, delay, unit);
    }


    public void testScheduleWithFixedDelay() {
        PrintTask5 printTask5 = new PrintTask5(5);
        scheduleWithFixedDelay(printTask5, 3, 3, TimeUnit.SECONDS);
    }

    public void testScheduleAtFixedRate() {
        PrintTask5 printTask5 = new PrintTask5(5);
        scheduleAtFixedRate(printTask5, 0, 2, TimeUnit.SECONDS);
    }

    public void testSingleThreadExecutor() {
        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 10; i++) {
            final int index = i;
            singleThreadExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("打印单线程任务 :" + index);
                }
            });
        }
    }


}

//打印任务
class PrintTask5 implements Runnable {
    public static final Logger log = LoggerFactory.getLogger(PrintTask5.class);
    final int index;

    PrintTask5(int index) {
        this.index = index;
    }

    @Override
    public void run() {
        try {
            log.info("打印任务:{} ,开始->当前时间: {} 当前线程id:{}", index, LocalDateTime.now(),
                    Thread.currentThread().getName());
        } catch (Exception e) {
            log.error("PrintTask5 : 异常!!!!! ");
            e.printStackTrace();
        }
    }
}

